package com.cctc.rds.raft.core.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.helpers.NOPLogger;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class RaftLogger {
    private static final Logger logger;

    static {
        Logger tmp = LoggerFactory.getLogger(RaftLogger.class);
        if (tmp instanceof NOPLogger) {
            tmp = (Logger) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class<?>[]{Logger.class}, new InvocationHandler() {
                @Override
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    if ("error".equals(method.getName())) {
                        System.err.println(formatMessage(args));
                    } else {
                        System.out.println(formatMessage(args));
                    }
                    return null;
                }
            });
        }
        logger = tmp;
    }

    private static String formatMessage(Object[] args) {
        String pmgs = (String) args[0];
        if (args.length > 1) {
            pmgs = pmgs.replace("{}", "%s");
            Object[] params;
            if (args.length == 2 && args[1].getClass().isArray()) {
                params = (Object[]) args[1];
            } else {
                params = new Object[args.length - 1];
                System.arraycopy(args, 1, params, 0, params.length);
            }
            pmgs = String.format(pmgs, params);
        }
        return pmgs;
    }

    public static Logger getLogger() {
        return logger;
    }

}
